package controllers

import (
	"supershare/backend/middleware"
	"supershare/backend/models"
	"supershare/backend/utils"

	"github.com/beego/beego/v2/core/logs"
	"github.com/beego/beego/v2/server/web"
)

// MiniCheckinController 小程序签到控制器
type MiniCheckinController struct {
	web.Controller
}

// 获取签到信息
func (c *MiniCheckinController) GetCheckinInfo() {
	user, err := middleware.GetCurrentMember(c.Ctx)
	if err != nil || user == nil {
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "未授权访问",
		}
		c.ServeJSON()
		return
	}
	// 从上下文获取用户信息
	memberId := c.Ctx.Input.GetData("user_id").(int64)

	// 检查今日是否已签到
	hasCheckin, err := models.CheckMemberCheckinToday(memberId)
	if err != nil {
		logs.Error("检查今日是否已签到失败: ", err)
		c.Data["json"] = utils.ResponseFail("获取签到信息失败: " + err.Error())
		c.ServeJSON()
		return
	}

	// 获取签到信息
	checkinInfo, err := models.GetMemberCheckinInfo(memberId)
	if err != nil {
		logs.Error("获取签到信息失败: ", err)
		c.Data["json"] = utils.ResponseFail("获取签到信息失败: " + err.Error())
		c.ServeJSON()
		return
	}

	// 获取会员积分
	member, err := models.GetMemberById(memberId, user.FranchiseId)
	if err != nil {
		logs.Error("获取会员信息失败: ", err)
		c.Data["json"] = utils.ResponseFail("获取会员信息失败: " + err.Error())
		c.ServeJSON()
		return
	}

	// 构建奖励列表
	rewardList := make([]map[string]interface{}, 0)
	dayNames := []string{"一", "二", "三", "四", "五", "六", "七"}

	for i := 0; i < 7; i++ {
		points := models.GetCheckinPointsReward(i)
		item := map[string]interface{}{
			"day":    dayNames[i],
			"points": points,
		}
		rewardList = append(rewardList, item)
	}

	// 返回签到信息
	c.Data["json"] = utils.ResponseSuccess("获取成功", map[string]interface{}{
		"checkinDays":     checkinInfo.ConsecutiveDays,
		"hasCheckedToday": hasCheckin,
		"userPoints":      member.Points,
		"totalDays":       checkinInfo.CumulativeDays,
		"rewardList":      rewardList,
	})
	c.ServeJSON()
}

// 执行签到
func (c *MiniCheckinController) DoCheckin() {
	user, err := middleware.GetCurrentMember(c.Ctx)
	if err != nil || user == nil {
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "未授权访问",
		}
		c.ServeJSON()
		return
	}
	// 从上下文获取用户信息
	memberId := c.Ctx.Input.GetData("user_id").(int64)

	// 获取客户端IP
	clientIp := c.Ctx.Input.IP()

	// 执行签到
	checkin, err := models.DoMemberCheckin(memberId, clientIp, user.FranchiseId)
	if err != nil {
		logs.Error("签到失败: ", err)
		c.Data["json"] = utils.ResponseFail("签到失败: " + err.Error())
		c.ServeJSON()
		return
	}

	// 获取会员信息（更新后的积分）
	member, err := models.GetMemberById(memberId, user.FranchiseId)
	if err != nil {
		logs.Error("获取会员信息失败: ", err)
	}

	// 判断是否第七天，获得特殊奖励
	isSpecialReward := checkin.Days == 7

	// 返回签到结果
	c.Data["json"] = utils.ResponseSuccess("签到成功", map[string]interface{}{
		"checkinDays":     checkin.Days,
		"points":          checkin.PointsReward,
		"userPoints":      member.Points,
		"isSpecialReward": isSpecialReward,
	})
	c.ServeJSON()
}

// 获取签到历史
func (c *MiniCheckinController) GetCheckinHistory() {
	// 从上下文获取用户信息
	memberId := c.Ctx.Input.GetData("user_id").(int64)

	// 获取查询参数
	year, _ := c.GetInt("year")
	month, _ := c.GetInt("month")

	// 获取签到历史
	checkins, err := models.GetMemberCheckinHistory(memberId, year, month)
	if err != nil {
		logs.Error("获取签到历史失败: ", err)
		c.Data["json"] = utils.ResponseFail("获取签到历史失败: " + err.Error())
		c.ServeJSON()
		return
	}

	// 格式化数据
	result := make([]map[string]interface{}, 0)
	for _, checkin := range checkins {
		item := map[string]interface{}{
			"date":   checkin.CheckinDate,
			"points": checkin.PointsReward,
			"days":   checkin.Days,
		}
		result = append(result, item)
	}

	// 返回签到历史
	c.Data["json"] = utils.ResponseSuccess("获取成功", map[string]interface{}{
		"list": result,
	})
	c.ServeJSON()
}
